package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.Permission;
import com.dropdb.demo.bean.Role;
import com.dropdb.demo.bean.RoleExample;
import com.dropdb.demo.bean.bo.AdminRoleListBO;
import com.dropdb.demo.bean.bo.AdminRolePermissionsBO;
import com.dropdb.demo.bean.vo.AdminRoleListData;
import com.dropdb.demo.bean.vo.AdminRoleOptionsData;
import com.dropdb.demo.bean.vo.PermissionData;
import com.dropdb.demo.config.SystemPermissionsConfig;
import com.dropdb.demo.mapper.PermissionMapper;
import com.dropdb.demo.mapper.RoleMapper;
import com.dropdb.demo.service.RoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    
    @Autowired
    RoleMapper roleMapper;

    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 分页获取角色信息
     * @param adminRoleListBo
     * @return
     */
    @Override
    public AdminRoleListData list(AdminRoleListBO adminRoleListBo) {
        RoleExample roleExample = new RoleExample();
        RoleExample.Criteria criteria = roleExample.createCriteria();
        if (null != adminRoleListBo.getName()) {
            criteria.andNameLike("%" + adminRoleListBo.getName() + "%");
        }
        criteria.andDeletedEqualTo(false);
        roleExample.setOrderByClause(adminRoleListBo.getSort() + " " + adminRoleListBo.getOrder());
        PageHelper.startPage(adminRoleListBo.getPage(), adminRoleListBo.getLimit());
        List<Role> roles = roleMapper.selectByExample(roleExample);
        PageInfo<Role> pageInfo = new PageInfo<>(roles);
        long total = pageInfo.getTotal();
        return new AdminRoleListData(roles, total);
    }

    /**
     * 添加角色
     * @param name
     * @param desc
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, timeout = 5)
    @Override
    public Role create(String name, String desc) {
        //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);
        Role role = new Role();
        role.setName(name);
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria()
                .andNameEqualTo(role.getName())
                .andDeletedEqualTo(false);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        if (null == roles || roles.isEmpty()) {
            role.setDesc(desc);
            role.setAddTime(new Date());
            role.setUpdateTime(role.getAddTime());
            roleMapper.insertSelective(role);
            role = roleMapper.selectByExample(roleExample).get(0);
            return role;
        }
        return null;
    }

    /**
     * 修改角色名称和描述
     * @param role
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, timeout = 5)
    @Override
    public int update(Role role) {
        if (null == role.getId()) {
            return -1;
        }
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria()
                .andNameEqualTo(role.getName())
                .andDeletedEqualTo(false);
        List<Role> roles = roleMapper.selectByExample(roleExample);

        //清空无关字段避免动态sql拼接
        role.setAddTime(null);
        role.setEnabled(null);
        role.setDeleted(null);

        if (null == roles || roles.isEmpty()) {
            return roleMapper.updateByPrimaryKeySelective(role);
        }
        return -2;
    }

    /**
     * 删除角色
     * @param role
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, timeout = 5)
    @Override
    public int delete(Role role) {
        if (null == role.getId()) {
            return -1;
        }
        Role toDb = new Role();
        toDb.setDeleted(true);
        toDb.setId(role.getId());
        return roleMapper.updateByPrimaryKeySelective(toDb);
    }

    /**
     * 查询所有角色
     * @return
     */
    @Override
    public List<AdminRoleOptionsData> options() {
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andDeletedEqualTo(false);
        List<Role> roles = roleMapper.selectByExample(roleExample);
        ArrayList<AdminRoleOptionsData> adminRoleOptionsDatas = new ArrayList<>(roles.size());
        for (Role role : roles) {
            adminRoleOptionsDatas.add(new AdminRoleOptionsData(role.getId(), role.getName()));
        }
        return adminRoleOptionsDatas;
    }


    @Resource(name = "sysPmConfig")
    SystemPermissionsConfig systemPermissionsConfig;

    @Override
    public PermissionData permissions(Integer roleId) {
        String sql = "select `permission` from `cskaoyanmall_permission` where `role_id` = ? and `deleted` = 0";
        List<String> permissions = jdbcTemplate.queryForList(sql, new Object[]{roleId}, String.class);
        PermissionData pd = new PermissionData();
        pd.setAssignedPermissions(permissions);
        pd.setSystemPermissions(systemPermissionsConfig.getSystemPermissions());
        return pd;
    }

    @Transactional
    @Override
    public int permissions(AdminRolePermissionsBO bo) {
        HashSet<String> pms = new HashSet<>(permissions(bo.getRoleId()).getAssignedPermissions());
        HashSet<String> bopms = new HashSet<>(bo.getPermissions());
        List<String> delete = new ArrayList<>();
        List<String> add = new ArrayList<>();

        for (String pm : bopms) {
            if (!pms.contains(pm)) {
                add.add(pm);
            }
        }
        for (String pm : pms) {
            if (!bopms.contains(pm)) {
                delete.add(pm);
            }
        }

        Integer roleId = bo.getRoleId();
        Date updateTime = new Date();
        String addSql = "insert into `cskaoyanmall_permission`(`role_id`,`permission`,`add_time`,`update_time`) values(?,?,?,?)";
        String deleteSql = "update `cskaoyanmall_permission` set `deleted`=true, `update_time`=? where `role_id`=? and `permission`=?";
        List<Object[]> args = new ArrayList<>();
        for (String pm : add) {
            args.add(new Object[]{roleId, pm, updateTime, updateTime});
        }
        int[] ints = jdbcTemplate.batchUpdate(addSql, args);

        args = new ArrayList<>();
        for (String pm : delete) {
            args.add(new Object[]{updateTime, roleId, pm});
        }
        int[] ints1 = jdbcTemplate.batchUpdate(deleteSql, args);
        return 1;
    }
}
